package com.guo.springboot.rabbitmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 * 生产者
 * @author guo
 * @date 2021/11/30 20:22 星期二
 **/
@Component
@Slf4j
public class RabbitSender {


    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 回调函数： Confirm函数
     */
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {

            log.info("================ Confirm 回调数据 ====================");
            log.info("Confirm 回调数据：" + correlationData);
            log.info("====================================");
            log.info("Confirm ack：" + ack);

            if (!ack){
                log.error("ack失败： " + cause);
            }

            log.info("================ Confirm 回调数据 over ====================");
        }
    };

    /**
     * 回调函数：return函数
     */
    final RabbitTemplate.ReturnsCallback returnsCallback = new RabbitTemplate.ReturnsCallback() {
        @Override
        public void returnedMessage(ReturnedMessage returned) {
            log.info("================ return 回调数据 开始 ====================");

            log.info("Exchange: " + returned.getExchange());
            log.info("ReplyText: " + returned.getReplyText());
            log.info("RoutingKey: " + returned.getRoutingKey());
            log.info("Message: " + returned.getMessage());
            log.info("ReplyCode: " + returned.getReplyCode());

            log.info("================ return 回调数据 结束 ====================");
        }
    };

    /**
     * 发消息
     * @param message 消息
     * @param properties 消息属性
     */
    public void send(Object message, Map<String,Object> properties){

        MessageHeaders messageHeaders = new MessageHeaders(properties);
        Message<Object> sendMsg = MessageBuilder.createMessage(message, messageHeaders);

        //添加回调函数
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnsCallback(returnsCallback);

        //生成ID 全局唯一 用于区分消息
        CorrelationData correlationData = new CorrelationData("msg123456:" + UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend("exchange-springboot-1","springboot.abc",sendMsg,correlationData);


    }



}
